import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from tkinter import messagebox as mBox

import UartPack as uart
from  DataChange import *



import serial
import serial.tools.list_ports
from tkinter import BOTH, END, LEFT



window=tk.Tk()
window.title('Main Window')
window.geometry()



uart_s = serial.Serial()
g_com=''


def uart_init():
    global uart_s
    try:
        uart_s.close()
    except:
        pass




def SelectCom(t,o=False):
    global uart_s
    try:
        uart_s.close()
    except:
        pass
    s=UartlistCombox.get()
    #print(s)
    selectport=''
    for i in s :
        if(i==' '):
            break
        else:
            selectport+=i
    #print(selectport[0:8])
    if('COM' in selectport ):
        #print(selectport)
        #print(s[-3:])
        if 'OK'in s[-3:]:
            print('on')
            uart_s=serial.Serial(selectport, 9600, timeout=60)
            uart_s.close()
            uart_list = uart.UartList()
            uart_list.insert(0, ['None', 'select no port'])
            UartlistCombox['values'] = uart_list  # 设置下拉列表的值
            global  g_com
            g_com=selectport
            return True
    return False


#串口接收显示的数据区域
from tkinter import scrolledtext        # 导入滚动文本框的模块




i,j=0,2
#baund select
tk.Label(window, text="baund").grid(row=0+i,column=0+j)
tmp = tk.StringVar()
tmp.set('9600')
e_baund = tk.Entry(window,width=7,textvariable=tmp)
e_baund.grid(row=0+i, column=1+j)

#stop bit
tk.Label(window, text="stop").grid(row=1+i,column=0+j)
svar = tk.StringVar()
c_stop=ttk.Combobox(window, width=3, textvariable=svar,state='readonly')
c_stop['values'] = ('1','1.5','2')
c_stop.grid(row=1+i,column=1+j)
print(c_stop['values'][0])
c_stop.current(0)
c_stop.set(c_stop['values'][0])

#data bit
tk.Label(window, text="data").grid(row=2+i,column=0+j)
svar = tk.StringVar()
c_data=ttk.Combobox(window, width=3, textvariable=svar,state='readonly')
c_data['values'] = ('8','7','6','5')
c_data.grid(row=2+i,column=1+j)
c_data.current(0)
c_data.set(c_data['values'][0])

#Parity
tk.Label(window, text="Parity").grid(row=3+i,column=0+j)
svar = tk.StringVar()
c_Parity=ttk.Combobox(window, width=3, textvariable=svar,state='readonly')
c_Parity['values'] = ('N','E','O')
c_Parity.grid(row=3+i,column=1+j)
c_Parity.current(0)
c_Parity.set(c_Parity['values'][0])

#串口选择的combox
uart_list=uart.UartList()
svar = tk.StringVar()
UartlistCombox = ttk.Combobox(window, width=70, textvariable=svar)
uart_list.insert(0,['None','select no port','ON'])
UartlistCombox['values'] = uart_list     # 设置下拉列表的值
UartlistCombox.grid(row=0,column=0,sticky='WN')      # 设置其在界面中出现的位置  column代表列   row 代表行
UartlistCombox.current(0)                 # 设置下拉列表默认显示的值，0为 numberChosen['values'] 的下标值
#UartlistCombox.bind('<<ComboboxSelected>>', SelectCom)
UartlistCombox.current(0)
UartlistCombox.set(UartlistCombox['values'][0])

#open uart
OpenUart_text = tk.StringVar()
a=0
OpenUart_text.set('Now is close')
def OpenUart():
    global  OpenUart_text
    if 'open'  in b_open['text']:
        global uart_s
        uart_s.close()
        OpenUart_text.set('Now is close')
    else:
        if(True==SelectCom('None',o=True)):
            OpenUart_text.set('Now is open')
            uart_s.timeout=1
            uart_s.xonxoff=0
            uart_s.port=g_com
            uart_s.parity=c_Parity.get()
            uart_s.baudrate=e_baund.get()
            uart_s.bytesize=int(c_data.get())
            uart_s.stopbits=int(c_stop.get())
            uart_s.open()



#打开串口的按钮
b_open=tk.Button(window, width=20, textvariable=OpenUart_text,command=OpenUart)
b_open.grid(row=0,column=1,sticky='N')



#receive txt 滚动文本框
scrolW = 100 # 设置文本框的长度
scrolH = 10 # 设置文本框的高度
getdata = tk.StringVar()
rectxt = scrolledtext.ScrolledText(window, width=scrolW, height=scrolH,)     # wrap=tk.WORD   这个值表示在行的末尾如果有一个单词跨行，会将该单词放到下一行显示,比如输入hello，he在第一行的行尾,llo在第二行的行首, 这时如果wrap=tk.WORD，则表示会将 hello 这个单词挪到下一行行首显示, wrap默认的值为tk.CHAR
rectxt.grid( row=1,column=0,columnspan=2,rowspan=20)        # columnspan 个人理解是将3列合并成一列   也可以通过 sticky=tk.W  来控制该文本框的对齐方式

#send txt
# t_send = tk.Text(window,width=scrolW,height=10)
# t_send.grid(row=22, column=0,rowspan=21,sticky='W')
sendtxt = scrolledtext.ScrolledText(window, width=scrolW, height=scrolH,)     # wrap=tk.WORD   这个值表示在行的末尾如果有一个单词跨行，会将该单词放到下一行显示,比如输入hello，he在第一行的行尾,llo在第二行的行首, 这时如果wrap=tk.WORD，则表示会将 hello 这个单词挪到下一行行首显示, wrap默认的值为tk.CHAR
sendtxt.grid(row=23, column=0,columnspan=2,rowspan=22,sticky='W')        # columnspan 个人理解是将3列合并成一列   也可以通过 sticky=tk.W  来控制该文本框的对齐方式

def senddata():
    if 'open' in b_open['text']:
        global uart_s
        uart_s.write(str2hexs(sendtxt.get(1.0,'end')))

b_send=tk.Button(window, width=20, text='send',command=senddata)
b_send.grid(sticky='SE')



uart_init()

c_stop.set(c_stop['values'][0])
c_data.set(c_data['values'][0])
c_Parity.set(c_Parity['values'][0])
UartlistCombox.set(UartlistCombox['values'][0])


import  threading
from multiprocessing import Process
import os

def get():
    while 1:
        global  uart_s
        if(uart_s.is_open):
            print('get')
            #temp='ss'
            temp = uart_s.read(1)
            print(temp)
            if(len(temp)):
                rectxt.insert(END, " in ScrolledText")


t = threading.Thread(target=get, name='LoopThread')
#t = Process(target=get, args=('test',))
t.start()





window.mainloop()